package com.wscx.jingjie.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.wscx.jingjie.entity.User;
import com.wscx.jingjie.jwt.Jwt;
import com.wscx.jingjie.service.UserService;
import com.wscx.jingjie.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;


/**
 * 登录controller
 **/
@Api(value = "登录controller", tags = {"登录操作接口"})
@RestController
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public JSONObject login(@RequestBody User loginUser,
            HttpServletRequest request) {

        logger.debug("用户登录 loginName={}", loginUser.getUsername());

        User user;
        user = userService.getUser( loginUser.getUsername());
        if (user == null) {
            return ResultUtil.setJson(1004, "用户名错误");
        }
        String md5Pwd = DigestUtils.md5DigestAsHex( loginUser.getPassword().getBytes());
        if (!Objects.equals(md5Pwd, user.getPassword())) {
            return ResultUtil.setJson(1004, "密码错误");
        }


        //创建token
        String token = Jwt.createToken(String.valueOf(user.getId()));

        //结果数据
        Map<String, Object> data = Maps.newHashMap();
        data.put("token", token);
        data.put("user", user);
        String remoteAddr = request.getRemoteAddr();
        data.put("ip", remoteAddr);
        return ResultUtil.setData(data);
    }


}
